package Guillermo_Santillan_CMSC137_Project;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.util.Date;
import java.text.*;

public class ChatApp extends javax.swing.JFrame implements ActionListener, Runnable {

    public ChatApp() {
        initServerComponents();

	clients = new ArrayList();
	setVisible(true);

	clientCount = 1;
	type = 1;
    }

    public ChatApp(String tit, String name, String ip, int portno){
	super(tit+name);
	initComponents();
	initGameBoard();

	setLocationRelativeTo(null);

	sendButton.addActionListener(this);
	playButton.addActionListener(this);
	quitButton.addActionListener(this);
	msgTF.addKeyListener(new KeyAdapter()
        {
            public void keyTyped(KeyEvent evt)
            { msgTFKeyTyped(evt);}
        });

	clientsList.add("Connected to Server...");
	clientsList.add("Currently Online:");
	setVisible(true);

	this.name = name;
	ctr = 0;
	clientCount = 1;
	type = 2;

	try{
		socket = new Socket(ip,portno);
		br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

		Date det = new Date();
		DateFormat dateF = new SimpleDateFormat("MM/dd/yyyy");
		DateFormat timeF = new SimpleDateFormat("HH:mm:ss");

		bw.write(name);bw.newLine(); bw.flush();
		String date = (name+ " has logged in at "+dateF.format(det)+" "+timeF.format(det));
		bw.write(date); bw.newLine(); bw.flush();
		Thread th;
		th = new Thread(this);
		th.start();
	}catch(Exception e){}
    }

    private void initServerComponents(){
	setLayout(new BorderLayout());
	clientsList = new java.awt.List(10);
	clientsSP = new javax.swing.JScrollPane();

	clientsList.add("Server Running...");
	clientsList.add("People Online:");
	clientsSP.setViewportView(clientsList);

	quitButton = new javax.swing.JButton("Close Server");
	quitButton.addActionListener(this);

	add(clientsSP, BorderLayout.CENTER);
	add(quitButton, BorderLayout.SOUTH);
	pack();
	setResizable(false);
    }

    private void initGameBoard(){
	int i=0;

	board = new int[9];
	buttons = new javax.swing.JButton[9];
	for(i=0; i<9; i++)
		buttons[i] = new javax.swing.JButton();

	box1.addActionListener(this);
	box2.addActionListener(this);
	box3.addActionListener(this);
	box4.addActionListener(this);
	box5.addActionListener(this);
	box6.addActionListener(this);
	box7.addActionListener(this);
	box8.addActionListener(this);
	box9.addActionListener(this);

	buttons[0] = box1;
	buttons[1] = box2;
	buttons[2] = box3;
	buttons[3] = box4;
	buttons[4] = box5;
	buttons[5] = box6;
	buttons[6] = box7;
	buttons[7] = box8;
	buttons[8] = box9;

	for(i=0; i<9; i++)
		board[i] = -1;
    }

    private void initComponents(){
        mainPanel = new javax.swing.JPanel();
        msgSP = new javax.swing.JScrollPane();
        msgTA = new javax.swing.JTextArea();
        clientsSP = new javax.swing.JScrollPane();
        clientsList = new java.awt.List();
        msgTF = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();
        gamePanel = new javax.swing.JPanel();
        box1 = new javax.swing.JButton();
        box2 = new javax.swing.JButton();
        box3 = new javax.swing.JButton();
        box4 = new javax.swing.JButton();
        box5 = new javax.swing.JButton();
        box6 = new javax.swing.JButton();
        box7 = new javax.swing.JButton();
        box8 = new javax.swing.JButton();
        box9 = new javax.swing.JButton();
        playButton = new javax.swing.JButton();
        quitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setResizable(false);

        msgTA.setColumns(20);
        msgTA.setEditable(false);
        msgTA.setRows(5);
        msgSP.setViewportView(msgTA);

        clientsSP.setViewportView(clientsList);
        sendButton.setText("SEND");
        gamePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Tic-Tac-Toe Game"));

        javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
        gamePanel.setLayout(gamePanelLayout);
        gamePanelLayout.setHorizontalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(gamePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(box4, 0, 0, Short.MAX_VALUE)
                    .addComponent(box1, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(box7, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(box8, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                    .addComponent(box5, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                    .addComponent(box2, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(box9, 0, 0, Short.MAX_VALUE)
                    .addComponent(box6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(box3, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE))
                .addContainerGap())
        );
        gamePanelLayout.setVerticalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(gamePanelLayout.createSequentialGroup()
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(box1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(box3, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(box2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(box5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(box6, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                    .addComponent(box4, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(box9, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                    .addComponent(box8, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                    .addComponent(box7, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                .addGap(12, 12, 12))
        );

        playButton.setText("Play");
        quitButton.setText("Quit");

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(msgTF, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
                    .addComponent(msgSP, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(clientsSP, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                    .addComponent(gamePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                            .addComponent(playButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(quitButton)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(msgSP, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                        .addComponent(clientsSP, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(gamePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(playButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton))
                    .addComponent(msgTF, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quitButton, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        pack();
    }

    public void run(){
	String msgg="";
	int opt, i;

	try{
			socket.setSoTimeout(1);
	}catch(Exception e){}
	while (true){
		try{
			msgg = br.readLine();
			if(msgg.equals("id_xxoxx")){
				ctr = 4;
			}
			else if(msgg.equals("698xx")){
				ctr = 1;
			}
			else if(msgg.equals("x9844")){
				ctr = 11;
			}
			else if(msgg.equals("16x28")){
				ctr = 2;
			}
			else if(msgg.equals("1x428")){
				ctr = 11;
			}
			else if(msgg.equals("Server_Exit_Connection_End")){
				System.exit(1);
			}
			else if(msgg.equals("play_req_xx199")){
				ctr = 3;
			}
			else if(msgg.equals("play_req_accept_xx199")){
				playButton.setEnabled(false);
				playState = clientPlaying;
				playPos = challenger;
				ctr = 6;
			}
			else if(msgg.equals("play_req_reject_xx199")){
				ctr = 11;
			}
			else if(msgg.equals("move_xx199")){
				ctr = 5;
			}
			else if(msgg.equals("play_end_winner_xx199")){
				for(i=0; i<9; i++){
					board[i] = -1;
					buttons[i].setText("");
					buttons[i].setEnabled(false);
				}
				playButton.setEnabled(true);
				playState = clientIdle;
				ctr = 11;
			}
			else if(msgg.equals("play_end_cat_xx199")){
				for(i=0; i<9; i++){
					board[i] = -1;
					buttons[i].setText("");
					buttons[i].setEnabled(false);
				}
				playButton.setEnabled(true);
				playState = clientIdle;
				ctr = 11;
			}
			else if(ctr==1){
				clientsList.add(msgg);
	    			clientCount++;
			}
			else if(ctr==2){
				clientsList.remove(Integer.parseInt(msgg));
				clientCount--;
			}
			else if(ctr==3){
				if(playState==clientIdle){
					opponentID = Integer.parseInt(msgg);
					opt = JOptionPane.showConfirmDialog(null,"Accept Tic-Tac-Toe Game Request??","Tic-Tac-Toe",JOptionPane.YES_NO_OPTION);
					if(opt==0){
						sendMsgToSomeone("play_req_accept_xx199", opponentID);
						sendMsgToSomeone(""+ownID, opponentID);
						playPos = challenged;
						playState = clientPlaying;
						playButton.setEnabled(false);
						msgTA.append("Tic-Tac-Toe: Game will start now. Please decide between yourselves who goes first."+"\n");
						msgTA.append("Tic-Tac-Toe: You will be "+playPos+", while your opponent will be "+((playPos+1)%2)+"\n");
						newGame();
					}
					else if(opt==1){
						sendMsgToSomeone(name+": I refuse to play at the moment. Please invite me some other time.", Integer.parseInt(msgg));
						sendMsgToSomeone("play_req_reject_xx199", Integer.parseInt(msgg));
					}
				}
				else{
					sendMsgToSomeone(name+" is currently playing with someone else!", Integer.parseInt(msgg));
				}
				ctr = 11;
			}
			else if(ctr==4){
				ownID = Integer.parseInt(msgg);
				ctr = 11;
			}
			else if(ctr==5){
				board[Integer.parseInt(msgg)] = (playPos+1)%2;
				buttons[Integer.parseInt(msgg)].setText(""+((playPos+1)%2));
				buttons[Integer.parseInt(msgg)].setEnabled(false);
				enableBoard(true);
				ctr = 11;
			}
			else if(ctr==6){
				opponentID = Integer.parseInt(msgg);
				msgTA.append("Tic-Tac-Toe: Game will start now. Please decide between yourselves who goes first."+"\n");
				msgTA.append("Tic-Tac-Toe: You will be "+playPos+", while your opponent will be "+((playPos+1)%2)+"\n");
				newGame();
				ctr = 11;
			}
			else
				msgTA.append(msgg+"\n");
		}catch (Exception h){}
	}
    }

    private boolean winner(int pos){
	if(pos==board[0] && pos==board[1] && pos==board[2]) return true;
	if(pos==board[0] && pos==board[4] && pos==board[8]) return true;
	if(pos==board[0] && pos==board[3] && pos==board[6]) return true;
	if(pos==board[1] && pos==board[4] && pos==board[7]) return true;
	if(pos==board[2] && pos==board[4] && pos==board[6]) return true;
	if(pos==board[2] && pos==board[5] && pos==board[8]) return true;
	if(pos==board[3] && pos==board[4] && pos==board[5]) return true;
	if(pos==board[6] && pos==board[7] && pos==board[8]) return true;
	return false;
    }

    private boolean draw(){
	int i=0;
	for(; i<9; i++){
		if(board[i]==-1) return false;
	}
	System.out.println("DRAW!!!");
	return true;
    }

    public void relayMsg(String msge, int rec){
	((ServerChat)clients.get(rec-2)).sendFromTo(msge);
    }

    public void enableBoard(boolean decision){
	int i=0;
	for(; i<9; i++){
		if(board[i]==-1){
			if(!decision)	buttons[i].setEnabled(false);
			if(decision)	buttons[i].setEnabled(true);
		}
	}
    }

    public void newGame(){
	int i=0;
	for(; i<9; i++){
		board[i] = -1;
		buttons[i].setText("");
	}
	enableBoard(true);
    }

    public void sendMsgToSomeone(String msge, int some){
	try{
		bw.write("33xx1");
		bw.newLine(); bw.flush();
		bw.write(""+some);
		bw.newLine(); bw.flush();
		bw.write(msge);
		bw.newLine(); bw.flush();
		bw.write("xx551");
		bw.newLine(); bw.flush();
	} catch(Exception kfg){}
    }
    
    public void acceptConnection(ChatApp app, int port) {
        try {
		server = new ServerSocket(port);
        }
        catch(IOException ioe) {
		System.exit(-1);
        }

        while(true) {
		try {
			Date det = new Date();
			DateFormat dateF = new SimpleDateFormat("MM/dd/yyyy");
			DateFormat timeF = new SimpleDateFormat("HH:mm:ss");
			int i=0;
			String temp="";
			socket = server.accept();
			inp = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			name = inp.readLine();

			clientsList.add(name);
			clientCount++;
			clients.add(new ServerChat(socket, msgTA, msgTF, name, clientCount, this));
		    
			for(; i<clientCount-2; i++){
				((ServerChat)clients.get(i)).sendFromTo(name+ " has logged in at "+dateF.format(det)+" "+timeF.format(det));
				((ServerChat)clients.get(i)).clientOnline(name);
				temp = ((ServerChat)clients.get(i)).getName();
				((ServerChat)clients.get(clientCount-2)).clientOnline(temp);
			}
			((ServerChat)clients.get(clientCount-2)).clientOnline(name);
			((ServerChat)clients.get(clientCount-2)).sendMsg("id_xxoxx");
			((ServerChat)clients.get(clientCount-2)).sendMsg(""+clientCount);
		}
		catch(IOException ioe) {
			System.exit(-1);
		}
        }
    }

    public void closeClientConnection(int id, String mess) {
	  int i=0;

	  for(i=id+1; i<=clientCount; i++){
		((ServerChat)clients.get(i-2)).setID(i-1);
		((ServerChat)clients.get(clientCount-2)).sendMsg("id_xxoxx");
		((ServerChat)clients.get(clientCount-2)).sendMsg(""+(i-1));
	  }

	  clientsList.remove(id);
	  clients.remove(id-2);
	  clientCount--;

	  for(i=0; i<clientCount-1; i++){
		((ServerChat)clients.get(i)).clientOffline(id);
		((ServerChat)clients.get(i)).sendFromTo(mess);
	  }
    }

    public static void main(String args[]) {
	int port;
	String type="", name="", ip;

	Object[] possibleValues = { "Server", "Client", "Exit" };
	Object selectedValue = JOptionPane.showInputDialog(null, "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);

	type = selectedValue.toString();

	if(type.equals("Server")){
		port = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Port Number: "));
		ChatApp app = new ChatApp();
        	app.setTitle("Server Application");
		app.acceptConnection(app, port);
	}

	if(type.equals("Client")){
		name = JOptionPane.showInputDialog(null, "Enter Chat Name: ");
		ip = JOptionPane.showInputDialog(null, "Enter IP Address: ");
		port = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Port Number: "));
		ChatApp app = new ChatApp("Client - ",name,ip,port);
	}
    }

    private javax.swing.JButton box1;
    private javax.swing.JButton box2;
    private javax.swing.JButton box3;
    private javax.swing.JButton box4;
    private javax.swing.JButton box5;
    private javax.swing.JButton box6;
    private javax.swing.JButton box7;
    private javax.swing.JButton box8;
    private javax.swing.JButton box9;
    private java.awt.List clientsList;
    private javax.swing.JScrollPane clientsSP;
    private javax.swing.JPanel gamePanel;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JScrollPane msgSP;
    private javax.swing.JTextArea msgTA;
    private javax.swing.JTextField msgTF;
    private javax.swing.JButton playButton;
    private javax.swing.JButton quitButton;
    private javax.swing.JButton sendButton;
    private ArrayList clients;
    private javax.swing.JButton buttons[];
    private java.awt.List timeList;
    ServerSocket server;
    Socket socket;
    BufferedReader inp;
    String name, serverName;
    int clientCount, ctr, type, board[], opponentID, ownID;
    int playState, clientPlaying=1, clientIdle=0;
    int playPos, challenger=0, challenged=1;
    BufferedReader br;
    BufferedWriter bw;

    private void enterSend(){
	sendMsgToSomeone(name+": "+msgTF.getText(), clientsList.getSelectedIndex());
	msgTA.append(name+": "+msgTF.getText()+"\n");
	msgTF.setText("");
    }

    private void msgTFKeyTyped(java.awt.event.KeyEvent evt) {
        if(evt.getKeyChar()==evt.VK_ENTER){
		if(clientsList.getSelectedIndex()>1 && !msgTF.getText().equals(""))
			enterSend();
	}
    }

    public void actionPerformed(ActionEvent e) {
	Date det = new Date();
	DateFormat dateF = new SimpleDateFormat("MM/dd/yyyy");
	DateFormat timeF = new SimpleDateFormat("HH:mm:ss");

	int i=0;

        if(e.getSource()==sendButton) {
		if(type==2){
			enterSend();
		}
        }

	if(e.getSource()==quitButton){
		if(type==1){
			for(i=0; i<clientCount-1; i++){
				((ServerChat)clients.get(i)).sendClose();
			}
			System.exit(1);
		}
		if(type==2){
			Date d2 = new Date();
			String logout = (name+ " has logged out at "+dateF.format(det)+" "+timeF.format(det));
			try{
				bw.write(logout); bw.newLine(); bw.flush();
				bw.write("LOGOUT_EXIT"); bw.newLine(); bw.flush();
				System.exit(1);
			}catch(Exception ed){}
		}
	}

	if(e.getSource()==playButton){
		if(clientsList.getSelectedIndex()>1 && clientsList.getSelectedIndex()!=ownID){
			sendMsgToSomeone("play_req_xx199", clientsList.getSelectedIndex());
			sendMsgToSomeone(""+ownID, clientsList.getSelectedIndex());
		}
	}

	for(i=0; i<9; i++){
		if(e.getSource()==buttons[i]){
			board[i] = playPos;
			buttons[i].setText(""+playPos);
			buttons[i].setEnabled(false);
			enableBoard(false);
			if(winner(playPos)){
				msgTA.append("Tic-Tac-Toe: You Tic-Tac-Won! Nice game!^_^");
				sendMsgToSomeone("Tic-Tac-Toe: You Tic-Tac-Lose! Sorry.", opponentID);
				sendMsgToSomeone("Tic-Tac-Toe: "+name+" Tic-Tac-Won the game! Still, it was a nice game!", opponentID);
				sendMsgToSomeone("play_end_winner_xx199", opponentID);
				playState = clientIdle;
				playButton.setEnabled(true);
				enableBoard(false);
			}
			else if(draw()){
				msgTA.append("Tic-Tac-Toe: CAT's GAME! Nice game both of you!"+"\n");
				sendMsgToSomeone("Tic-Tac-Toe: CAT's GAME! Nice game both of you!", opponentID);
				sendMsgToSomeone("play_end_cat_xx199", opponentID);
				playState = clientIdle;
				playButton.setEnabled(true);
				enableBoard(false);
			}
			else{
				sendMsgToSomeone("move_xx199", opponentID);
				sendMsgToSomeone(""+i, opponentID);
			}
		}
	  }
    }

}